﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace wsErrorsLog
{
    public class Parameters
    {
        public int? LastErrorIdSynced;

    }

    public class ErrorDetailsDTO
    {
        public int UniqueId;
        public String InitialCallStack;
        public String WindowsUserName;
        public long LogDate;
        public bool HasScreenShot;
        public String Message;


        public static ErrorDetailsDTO[] CalculateErrors(int? iLastSyncedErrorId)
        {
            List<ErrorDetailsDTO> list = new List<ErrorDetailsDTO>();
            string connectionString = @"Data Source=109.104.65.8\sqlexpress;Initial Catalog=ABMServiceStatistics;Persist Security Info=True;User ID=ABMTestUser;Password=ABMTestUser";
            SqlParameter[] aParams = new SqlParameter[1];
            aParams[0] = new SqlParameter("@LastSyncedErrorId", iLastSyncedErrorId.GetDBValue());            
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand comm = con.CreateCommand())
                {
                    comm.Parameters.AddRange(aParams);
                    comm.CommandText = "GetLastExceptionsBasicDetails";
                    comm.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    using(var reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            DateTime logDate = (DateTime)reader["LogDate"];
                            ErrorDetailsDTO error = new ErrorDetailsDTO
                            {
                                HasScreenShot = (bool)reader["HasScreenShot"],
                                InitialCallStack = reader["StackTrace"].ToString(),
                                LogDate = Utilities.ConvertDateTime(logDate).Value,
                                Message = reader["Message"].ToString(),
                                UniqueId = (int)reader["UniqueId"],
                                WindowsUserName = reader["WindowsUserName"] == DBNull.Value ? null : (string)reader["WindowsUserName"]
                            };
                            list.Add(error);
                        }
                    }
                }
            }
            return list.ToArray();
        }
    }
}
